﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using FRL.DebtChased.Repository;

namespace FRL.DebtChased.ServiceUtilities
{

	/// <summary>
	/// Declaration of LogFile class
	/// </summary>
	public static class LogFile
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		private static object m_oLock = new object();

		private static string m_strLogFilepath;

		/////////////////////////////////////////////////////////////
		// Static Construction

		static LogFile()
		{

			// Compose the log filepath
			m_strLogFilepath = ConfigurationManager.AppSettings["LogFilePath"];

		}

		/////////////////////////////////////////////////////////////
		// Static Operations

		public static void Append(string strMessage)
		{

			// Compose a line for the file
			string strLine = string.Format("{0} {1}", DateTime.Now, strMessage);

			// Prevent thread-clash
			lock (m_oLock)
			{

				// Add to file
				File.AppendAllText(m_strLogFilepath, string.Format("{0}\r\n",strLine));

			}

			// Dump to console
#if CONSOLEMODE
			Console.WriteLine(strLine);
#endif // #if CONSOLEMODE

		}

		public static void Append(Exception x)
		{

			// Compose exception details
			StringBuilder sb = new StringBuilder();
			sb.Append(x.Message);
			if (x.InnerException != null)
				sb.AppendFormat("  INNER EXCEPTION: {0}", x.InnerException);

			// Call sibling function
			Append(sb.ToString());

		}

		public static void Append( AccountNote newNote )
		{

			// Compose a message
			if(string.IsNullOrEmpty(newNote.Error))
				Append(newNote.Narrative);
			else
				Append(string.Format("{0} ERROR:{1}",newNote.Narrative,newNote.Error));

		}

	}

}
